package com.nbsaas.boot.queue.queue;

import com.nbsaas.boot.queue.task.Task;

import java.util.PriorityQueue;
import java.util.concurrent.locks.ReentrantLock;

public class TaskQueue {
    private final PriorityQueue<Task> queue;
    private final ReentrantLock lock;

    public TaskQueue() {
        this.queue = new PriorityQueue<>((t1, t2) -> {
            int timeCompare = t1.getExecuteTime().compareTo(t2.getExecuteTime());
            if (timeCompare != 0) {
                return timeCompare;
            }
            return Integer.compare(t2.getPriority(), t1.getPriority());
        });
        this.lock = new ReentrantLock();
    }

    public void addTask(Task task) {
        lock.lock();
        try {
            queue.offer(task);
        } finally {
            lock.unlock();
        }
    }

    public Task getNextTask() {
        lock.lock();
        try {
            return queue.peek();
        } finally {
            lock.unlock();
        }
    }

    public Task removeNextTask() {
        lock.lock();
        try {
            return queue.poll();
        } finally {
            lock.unlock();
        }
    }

    public boolean isEmpty() {
        lock.lock();
        try {
            return queue.isEmpty();
        } finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }
} 